﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using BookDownloader.Core.Behaviour;

namespace BookDownloader.Core.Implementation
{
	public class ProjectRepository
	{
		public void Save(string filename, IProject project)
		{
			Stream stream = null;
			try
			{
				stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
				IFormatter formatter = new BinaryFormatter();
				formatter.Serialize(stream, project);
			}
			finally
			{
				if (stream != null)
					stream.Close();
			}

		}

		public Project Load(string filename)
		{
			Stream stream = null;
			Project project = null;
			try
			{
				stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
				IFormatter formatter = new BinaryFormatter();
				// ключевой момент: копируем в новый объект все поля из загруженного
				project = (Project)formatter.Deserialize(stream);
			}
			finally
			{
				if (null != stream)
					stream.Close();
			}
			return project;
		}
	}
}
